package com.atguigu.gulimall.cart.interceptor;

import com.atguigu.common.constant.AuthConstant;
import com.atguigu.common.constant.CartConstant;
import com.atguigu.common.vo.MemberVo;
import com.atguigu.gulimall.cart.to.UserInfoTo;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

public class CartInterceptor implements HandlerInterceptor {
    public static ThreadLocal<UserInfoTo> threadLocal = new ThreadLocal<>();
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
        //判断用户是否登录
        HttpSession session = request.getSession();
        MemberVo attribute = (MemberVo) session.getAttribute(AuthConstant.LOGIN_USER);
        UserInfoTo userInfoTo = new UserInfoTo();
        if(attribute!=null){
            //用户已经登录
            userInfoTo.setUserId(attribute.getId());
        }
        //判断是否携带临时用户cookie
        Cookie[] cookies = request.getCookies();
        if(cookies!=null&&cookies.length>0){
            for (Cookie cookie : cookies) {
                if(cookie.getName().equals(AuthConstant.TEMP_USER_NAME)){
                    userInfoTo.setUserKey(cookie.getValue());
                    userInfoTo.setIsTempUser(true);
                }
            }
        }

        if(!userInfoTo.getIsTempUser()){
            //没有临时用户，自动生成一个
            String uuid = UUID.randomUUID().toString();
            userInfoTo.setUserKey(uuid);
        }
        threadLocal.set(userInfoTo);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response,
                           Object handler, ModelAndView modelAndView) throws Exception {
        UserInfoTo userInfoTo = threadLocal.get();
        if(!userInfoTo.getIsTempUser()){
            //没有临时用户的cookie，则在浏览器生成
            Cookie cookie = new Cookie(AuthConstant.TEMP_USER_NAME,userInfoTo.getUserKey());
            cookie.setDomain("gulimall.com");
            cookie.setMaxAge(CartConstant.MAX_AGE);
            response.addCookie(cookie);
        }
        return;
    }
}
